<template>
    <div>
        <el-form label-width="110px" size="small">
            <el-row class="form-row">
                <el-col :span="12">
                    <el-form-item label="产品代码:">
                        <RiskEntryInput id="fundCode" @set-entry-data="getEntryslist" :returnDatas="instruction.fundCode" />
                        <!-- <el-select v-model="instruction.fundCode" filterable @change="handleFundCodeChange" size="mini">
                            <el-option v-for="i in fundCodeSelectData" :key="i.fundCode" :label="i.fundCode + ' ' + i.fundNameSt" :value="i.fundCode">
                            </el-option>
                        </el-select> -->
                    </el-form-item>
                    <el-form-item label="资产单元编号:" v-show="SHOW_SECURITY">
                        <el-select v-model="instruction.assetCode" size="mini">
                            <el-option
                                v-for="i in computedAssetCodeSelectData"
                                :key="i.assetCode"
                                :label="i.assetCode + ' ' + i.assetName"
                                :value="i.assetCode"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="组合编码:">
                        <el-select name="fundAccountCode" v-model="instruction.fundAccountCode" size="mini" @change="handleFundAccountCodeChange">
                            <el-option
                                v-for="i in computedFundAccountCodeSelectData"
                                :key="i.fundAccountCode"
                                :label="i.fundAccountCode + ' ' + i.fundAccountName"
                                :value="i.fundAccountCode"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="证券代码:">
                        <el-select
                            name="stockCode"
                            v-model="instruction.stockCode"
                            @change="handleStockCode"
                            filterable
                            @visible-change="handleStockVisibleChange"
                            :filter-method="getstockCodeList"
                            :loading="selectLoading"
                            size="mini"
                            clearable
                            @clear="getstockCodeList('')"
                        >
                            <el-option
                                v-for="i in stockCodeSelectData"
                                :key="i.dictKey"
                                :label="i.dictKey + ' ' + i.dictKeyName"
                                :value="i.dictKey"
                                :name="'stockCode' + i.dictKey"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="业务类型:">
                        <el-select name="businessType" v-model="instruction.businessType" size="mini" disabled>
                            <el-option label="债券一级市场" value="D"> </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="委托方向:">
                        <el-select name="orderDirection" v-model="instruction.orderDirection" size="mini" disabled :class="['font-color-' + 'red']">
                            <el-option label="分销买入" value="K"> </el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="目标类型:">
                        <el-select name="targetType" v-model="instruction.targetType" size="mini" disabled>
                            <el-option v-for="(value, key) in targetTypePojo" :key="key" :label="value" :value="key"> </el-option>
                        </el-select>
                    </el-form-item>
                    <!-- <el-form-item label="投标方式:">
                        <el-select v-model="instruction.tenderWay" size="mini">
                            <el-option label="一级缴款" value="1"> </el-option>
                            <el-option label="上市买入" value="2"> </el-option>
                        </el-select>
                    </el-form-item> -->
                </el-col>
                <el-col :span="12">
                    <el-form-item label="投标方式:">
                        <el-select name="tenderWay" v-model="instruction.tenderWay" size="mini">
                            <el-option label="一级缴款" value="1"> </el-option>
                            <el-option label="上市买入" value="2"> </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="招标标的:">
                        <el-select name="subject" v-model="instruction.subject" size="mini" disabled>
                            <el-option v-for="i in subjectSelectData" :key="i.value" :label="i.label" :value="i.value" :name="'subject' + i.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item v-if="instruction.subject === '' || instruction.subject === '3'" label="价格:">
                        <RiskInputNumber
                            name="orderPrice"
                            style="margin-top: 3px"
                            :input="instruction.orderPrice"
                            :inputAfter="'元'"
                            :colorStyle="textColor"
                            :precision="2"
                            :maxlength="15"
                            :field="'orderPrice'"
                            @getInputNumber="getInputNumber(arguments)"
                        >
                        </RiskInputNumber>
                        <!-- <el-input v-model="instruction.orderBalance" :disabled="orderBalanceStatus"></el-input> -->
                    </el-form-item>

                    <el-form-item v-else label="利率:">
                        <RiskInputNumber
                            name="orderPrice"
                            style="margin-top: 3px"
                            :input="instruction.orderPrice"
                            :inputAfter="'%'"
                            :precision="2"
                            :maxlength="15"
                            :field="'orderPrice'"
                            @getInputNumber="getInputNumber(arguments)"
                        >
                        </RiskInputNumber>
                        <!-- <el-input v-model="instruction.orderBalance" :disabled="orderBalanceStatus"></el-input> -->
                    </el-form-item>
                    <el-form-item label="投标金额:">
                        <RiskInputNumber
                            name="orderBalance"
                            :input="instruction.orderBalance"
                            :inputAfter="'万元'"
                            :colorStyle="textColor"
                            :precision="4"
                            :maxlength="15"
                            :field="'orderBalance'"
                            @getInputNumber="getInputNumber(arguments)"
                        >
                        </RiskInputNumber>
                    </el-form-item>
                    <el-form-item label="上市日期">
                        <el-date-picker
                            name="listDate"
                            disabled
                            v-model="instruction.listDate"
                            type="date"
                            format="yyyy-MM-dd"
                            value-format="yyyyMMdd"
                            style="width: 100%"
                            placeholder="请选择"
                        ></el-date-picker>
                    </el-form-item>
                    <el-form-item label="缴款日期">
                        <el-date-picker
                            name="payDate"
                            disabled
                            v-model="instruction.payDate"
                            type="date"
                            format="yyyy-MM-dd"
                            value-format="yyyyMMdd"
                            style="width: 100%"
                            placeholder="请选择"
                        ></el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
    </div>
</template>

<script lang="ts">
import Invest from '@/common/dict/invest';
import DictionConstUtil, { objToArr, SGU_CACHE } from '@/utils/diction-const-util';
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import RiskInputNumber from '@/pages/risk-measure/components/risk-input-number.vue';
import { SelectOptionItemData } from '@/pages/risk-time/types/SelectOptionItemData';
import { getBusinessType } from '@/pages/risk-time/api';
import { Dictionary } from '@/pages/risk-time/types/Dictionary';
import RiskEntryInput from '@/common/components/risk-entry-input.vue';
import { getConfigItem, uniqueFunc } from '@/utils/tools';

@Component({
    name: 'PrimaryBondBidOrder',
    components: {
        RiskInputNumber,
        RiskEntryInput,
    },
})

// 场外基金指令
export default class PrimaryBondBidOrder extends Vue {
    @Prop()
    detail: any;
    @Prop()
    renderCount: number;
    @Prop()
    stockInfoCache: any;
    Invest: any = new Invest();
    selectLoading: boolean = false; // 下拉框远程搜索时的加载状态
    fundCodeSelectData: any[] = []; // 产品序号下拉框数据
    fundAccountCodeSelectData: any[] = []; // 组合编码下拉框数据
    // allStockType: any[] = [];
    orderDirectionSelectData: any[] = []; // 订单方向下拉框数据
    subjectSelectData: any[] = [
        {
            value: '1',
            label: '利率',
        },
        {
            value: '3',
            label: '价格',
        },
    ]; // 招标标的下拉框数据

    businessSelectData: SelectOptionItemData[] = [];

    investPriceSelectData: any[] = []; // 价格模式下拉框数据
    stockCodeSelectData: any[] = []; // 证券代码下拉框数据

    orderAmountStatus: boolean = false;
    orderBalanceStatus: boolean = false;

    private instruction = {
        fundCode: '', // 产品代码
        fundAccountCode: '', // 组合编码
        reportCode: '', // 申报代码
        orderDirection: 'K', // 委托方向
        stockCode: '', // 证券代码
        businessType: 'D',
        businessTypeName: 'D',
        orderAmount: '', // 指令数量
        orderPrice: '', // 指令价格
        orderBalance: '', // 指令金额
        fundNameSt: '',
        fundAccountName: '',
        assetCode: '',
        assetName: '',
        subject: '', // 招标标的
        // stockFaceBalance: '',
        listDate: '',
        payDate: '',
        tenderWay: '1', // 招标方式
        targetType: '2',
    };
    stockInfo: any = {};
    textColor: string = 'red';
    targetTypePojo: any = {}; // 目标类型

    async mounted() {
        // 获取目标类型
        this.targetTypePojo = DictionConstUtil.targetType;
        // 获取产品信息 (产品序号下拉框数据)
        this.fundCodeSelectData = await SGU_CACHE('FundInfo', '/fundInfo/list', []);
        // 获取组合编码下拉框数据
        let arr = await SGU_CACHE('FundAccount', '/fundInfo/accounts', []);
        arr.forEach(item => {
            this.fundAccountCodeSelectData[item.fundCode] = item.fundAccounts;
        });
        // 获取价格模式下拉框数据
        this.investPriceSelectData = await SGU_CACHE('PriceType', '/dict/list/code/Y_000237', []);
        // 获取证券代码下拉框数据
        this.getstockCodeList('');
    }

    @Watch('instruction', { immediate: true, deep: true })
    setValues() {
        this.$emit(
            'handleSettingValue',
            {
                ...this.instruction,
                orderBalance: Number(this.instruction.orderBalance || '0') * 10000,
            },
            '10'
        );
    }

    @Watch('stockInfoCache', { immediate: true, deep: true })
    onWatchStockInfo() {
        if (this.stockInfoCache) {
            this.stockInfo = this.stockInfoCache;
            this.getstockCodeList(this.stockInfo.stockCode);
        }
    }

    SHOW_SECURITY = getConfigItem('SHOW_SECURITY');
    // 监听 资产单元计算属性 (每当计算属性变动时 自动选中第一项)
    @Watch('computedAssetCodeSelectData', { immediate: true, deep: true })
    watchcomputedAssetCode(newData) {
        if (!this.SHOW_SECURITY) {
            return;
        }
        let obj: any = {};
        if (newData && newData.length) {
            const d1 = newData.find(item => item.assetCode == this.instruction.assetCode);
            obj = d1 || newData[0];
        }
        this.instruction.assetCode = obj.assetCode;
        this.instruction.assetName = obj.assetName;
    }

    // 监听 组合编码计算属性 (每当计算属性变动时 自动选中第一项)
    @Watch('computedFundAccountCodeSelectData', { immediate: true, deep: true })
    watchcomputedFundAccountCode(newData) {
        let obj: any = {};
        if (newData && newData.length) {
            const d1 = newData.find(item => item.fundAccountCode == this.instruction.fundAccountCode);
            obj = d1 || newData[0];
        }
        this.instruction.assetCode = obj.assetCode;
        this.instruction.assetName = obj.assetName;
        this.instruction.fundAccountCode = obj.fundAccountCode;
        this.instruction.fundAccountName = obj.fundAccountName;
    }

    get computedAssetCodeSelectData(): any {
        return uniqueFunc(this.fundAccountCodeSelectData[this.instruction.fundCode], 'assetCode');
    }

    // 组合编码下拉框计算属性;
    get computedFundAccountCodeSelectData() {
        let data = this.fundAccountCodeSelectData[this.instruction.fundCode];
        let retData = [];
        if (data && this.SHOW_SECURITY) {
            const obj = data.filter(item => item.assetCode == this.instruction.assetCode);
            retData = obj || [];
        } else {
            retData = data;
        }
        return retData;
    }

    @Watch('renderCount', { immediate: true, deep: true })
    async setForm() {
        if (this.detail && Object.keys(this.detail).length) {
            let instruction = this.detail;
            // 获取组合编码下拉框数据
            let arr = await SGU_CACHE('FundAccount', '/fundInfo/accounts', []);
            arr.forEach(item => {
                this.fundAccountCodeSelectData[item.fundCode] = item.fundAccounts;
            });

            for (const key in instruction) {
                this.instruction[key] = instruction[key];
            }
            this.instruction.orderBalance = (Number(this.instruction.orderBalance || 0) / 10000).toString();
            await this.getstockCodeList(this.detail.stockCode);

            let stock = this.stockCodeSelectData.find(item => item.dictKey === this.detail.stockCode);

            if (stock && stock.bondInfo) {
                this.stockInfo = stock.bondInfo;
                this.stockInfo.stockNameSt = stock.dictKeyName;
                this.instruction.reportCode = this.stockInfo.reportCode;
                this.instruction.listDate = this.stockInfo.listDate;
                this.instruction.payDate = this.stockInfo.payDate;
                if (this.stockInfo.bidObject) {
                    this.instruction.subject = this.stockInfo.bidObject;
                } else {
                    this.instruction.subject = '3';
                }
            }
        }
    }

    getInputNumber(args: any) {
        let value = args[0];
        let field = args[1];
        this.instruction[field] = value;
        // if (field === 'stockFaceBalance' || field === 'orderPrice') {
        //     // 指令数量 = 券面总额*10000/当前面值
        //     let amount = (Number(this.instruction.stockFaceBalance || 0) * 10000) / Number(this.stockInfo.facePrice || 0);
        //     this.instruction.orderAmount = amount.toString() || '0';
        //     // 投标金额=券面总额*10000/当前面值*价格or利率(%)
        //     if (this.instruction.subject === '3') {
        //         this.instruction.orderBalance = ((amount * Number(this.instruction.orderPrice || 0)) / 10000).toString();
        //     } else {
        //         this.instruction.orderBalance = ((amount * Number(this.instruction.orderPrice || 0)) / 10000 / 100).toString();
        //     }
        // } else if (field === 'orderBalance') {
        //     if (this.instruction.subject === '3') {
        //         this.instruction.orderPrice = (
        //             (Number(this.instruction.orderBalance || 0) * 10000) /
        //             Number(this.instruction.orderAmount || 0)
        //         ).toString();
        //     } else {
        //         this.instruction.orderPrice = (
        //             ((Number(this.instruction.orderBalance || 0) * 10000) / Number(this.instruction.orderAmount || 0)) *
        //             100
        //         ).toString();
        //     }
        // }
    }

    getEntryslist(val: any) {
        this.instruction.fundCode = val;
        this.handleFundCodeChange(val);
    }

    handleFundCodeChange(val: string): void {
        let fund = this.fundCodeSelectData.find(item => item.fundCode === val) || {};
        let fundAccount = (this.fundAccountCodeSelectData[this.instruction.fundCode] || [])[0] || {};
        this.instruction.fundNameSt = fund.fundNameSt;
        this.instruction.fundAccountCode = fundAccount.fundAccountCode;
        this.instruction.fundAccountName = fundAccount.fundAccountName;
        this.instruction.assetCode = fundAccount.assetCode;
        this.instruction.assetName = fundAccount.assetName;
    }

    handleFundAccountCodeChange(value: string) {
        let fundAccount = (this.fundAccountCodeSelectData[this.instruction.fundCode] || []).find(item => item.fundAccountCode === value) || {};
        this.instruction.fundAccountName = fundAccount.fundAccountName;
        this.instruction.assetCode = fundAccount.assetCode;
        this.instruction.assetName = fundAccount.assetName;
    }

    handleStockCode(stockCode: string): void {
        this.stockInfo = {};
        this.instruction.reportCode = '';
        this.instruction.listDate = '';
        this.instruction.payDate = '';
        this.instruction.subject = '';
        this.instruction.orderPrice = '';
        this.instruction.orderBalance = '';
        if (stockCode) {
            let stock = this.stockCodeSelectData.find(item => item.dictKey === stockCode);
            if (stock && stock.bondInfo) {
                this.stockInfo = stock.bondInfo;
                this.stockInfo.stockNameSt = stock.dictKeyName;
                this.instruction.reportCode = this.stockInfo.reportCode;
                this.instruction.listDate = this.stockInfo.listDate;
                this.instruction.payDate = this.stockInfo.payDate;
                if (this.stockInfo.bidObject) {
                    this.instruction.subject = this.stockInfo.bidObject;
                } else {
                    this.instruction.subject = '3';
                }

                // 给 价格 || 利率 赋上默认值
                if (this.instruction.subject === '' || this.instruction.subject === '3') {
                    this.instruction.orderPrice = '100';
                } else {
                    this.instruction.orderPrice = '1';
                }
            }
            this.$emit('getStockInfo', this.stockInfo, '10');
        }
    }

    handleStockVisibleChange(val) {
        if (!val) {
            this.getstockCodeList('');
        }
    }

    // 获取证券代码下拉框数据
    async getstockCodeList(val: string | undefined) {
        this.selectLoading = true;
        await this.$axios
            .post('/dict/bond/select', {
                bondInfo: {
                    bidTag: 1,
                },
                dictKey: val,
                dictKeyName: val,
            })
            .then((res: any) => {
                this.stockCodeSelectData = res || [];
                this.selectLoading = false;
            });
    }
}
</script>
<style lang="scss" scoped>
@import '@/pages/risk-measure/style/measure';

.form-row {
    margin-top: 3px;
    .el-form-item--small {
        margin: 0;
        & /deep/ .el-form-item__label {
            color: #575757;
        }
        & /deep/ .el-input__inner {
            height: 28px;
            line-height: 28px;
        }
        .font-color-red {
            /deep/ input {
                color: red !important;
            }
            /deep/ .el-input-group__append {
                color: red !important;
            }
        }
    }
}
</style>
